package chpt02;

import java.util.Arrays;
import java.util.Random;

public class StudentGradeManagement {

	public static void main(String[] args) {
		int numStu = 5;    // 学生个数
		int numCourse = 3; // 科目个数
		String bar = "*".repeat(5); // 5个*
		String[] sNames = generateStudentNames(numStu);
		String[] cNames = { "语文", "数学", "英语" };
		Integer[][] grades = generateRandomGrades(numStu, numCourse);
		
		System.out.println("学生名单: " + Arrays.toString(sNames));
		// 打印成绩单
		System.out.println(bar + "成绩单" + bar);
		printAllGrades(cNames, sNames, grades);
		
		// 打印平均成绩
		System.out.println(bar + "平均成绩" + bar);
		for (int i = 0; i < numCourse; i++) {
			System.out.println(cNames[i] + " = " + calAvg(grades, i));
		}
	}
	
	public static String[] generateStudentNames(int numStu) {
		String[] studentNames = new String[numStu];
		for (int i = 0; i < numStu; i++) {
			studentNames[i] = "学生" + (i + 1);
		}
		return studentNames;
	}

	public static Integer[][] generateRandomGrades(int numStu, int numCourse) {
		Integer[][] grades = new Integer[numStu][numCourse];
		// 101是生成随机数的种子，种子一样可保证每次生成的随机数序列都一样
		Random random = new Random(101);
		for (int i = 0; i < numStu; i++) {
			for (int j = 0; j < numCourse; j++) {
				if (random.nextInt(10) == 0) { // 平均每生成10个成绩，就有一个为null
					grades[i][j] = null;
				} else {
					grades[i][j] = random.nextInt(101); // 生成0-100的随机数
				}
			}
		}
		return grades;
	}

	public static void printAllGrades(String[] cNames, String[] names, Integer[][] grades) {
		String fmt = "%s\t%s\t%s\t%s\t%n"; // 格式化字符串.%s字符串，%n回车换行
		System.out.printf(fmt, "姓名", cNames[0], cNames[1], cNames[2]);
		for (int i = 0; i < names.length; i++) {
			System.out.printf(fmt, names[i], grades[i][0], grades[i][1], grades[i][2]);
		}
	}

	public static double calAvg(Integer[][] grades, int courseId) {
		int sum = 0;
		int count = 0;
		for (Integer[] grade : grades) { // 二维数组每一行是一维数组
			if (grade[courseId] != null) {
				sum += grade[courseId];
				count++;
			}
		}
		return count > 0 ? (double) sum / count : 0;
	}
}